from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declared_attr

from fastapi_common.db.base_class import Base


class Menu(Base):
    id = Column(Integer, primary_key=True, autoincrement=True)
    menu_name = Column(String(length=255), comment='菜单名')
    menu_route = Column(String(length=255), comment='菜单路由，前端使用')
    menu_icon = Column(String(length=255), comment='菜单图片，前段使用')
    menu_order = Column(Integer, comment='菜单顺序')
    parent_id = Column(Integer, index=True)
    # sub_menus = relationship('Menu')
    # role_menus = relationship('RoleMenu', back_populates='menu')


class RoleMenu(Base):
    id = Column(Integer, primary_key=True, autoincrement=True)
    role_id = Column(Integer)
    menu_id = Column(Integer)
    # 不使用外键关联，分部查询更直观
    # menu_id = Column(Integer, ForeignKey("menu.id"))
    # role_id = Column(Integer, ForeignKey("role.id"))
    # menu = relationship('Menu', back_populates='role_menus')
    # role = relationship('Role', back_populates='role_menus')

    __table_args__ = (
        UniqueConstraint('role_id', 'menu_id'),
    )

    @declared_attr
    def __tablename__(cls) -> str:
        return 'role_menu'
